package com.kevin.hw.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.concurrent.TimeUnit;

/**
 * @author: kevin
 * @date: 2017/8/15
 * @description:
 */
public class MasterSelector {

    private final static String CONNECT_STRING = "localhost:2181";

    private final static String MASTER_PATH = "/curator_master";

    public static void main(String[] args) {

        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder()
                .connectString(CONNECT_STRING)
                .retryPolicy(new ExponentialBackoffRetry(1000,3))
                .build();

        LeaderSelector leaderSelector = new LeaderSelector(curatorFramework, MASTER_PATH, new LeaderSelectorListenerAdapter() {
            @Override
            public void takeLeadership(CuratorFramework curatorFramework) throws Exception {
                System.out.println("获取Leader成功");
                TimeUnit.SECONDS.sleep(3);
            }
        });

        leaderSelector.autoRequeue();
        leaderSelector.start();
    }
}
